export default {
	namespaced: true,
	// 加入购物车的数据
	state: () => ({
		cart: JSON.parse(uni.getStorageSync('cart') || '[]')
	}),
	mutations: {
		addToCart(state, goods) {
			const result = state.cart.find(item => item.goods_id === goods.goods_id)
			if (result) {
				result.goods_count += 1
			} else {
				state.cart.push(goods)
			}
			this.commit('m_cart/saveToStorage')
		},
		// 保存在本地
		saveToStorage(state) {
			uni.setStorageSync('cart', JSON.stringify(state.cart))
		},
		// 修改购物车的商品状态
		updateGoodsState(state, goods) {
			const result = state.cart.find(item => item.goods_id === goods.goods_id)
			if (result) {
				result.goods_state = goods.goods_state
				this.commit('m_cart/saveToStorage')
			}
		},
		// 修改购物车的商品数量
		updateGoodsNumber(state, goods) {
			const result = state.cart.find(item => item.goods_id === goods.goods_id)
			if (result) {
				result.goods_count = goods.goods_count
				this.commit('m_cart/saveToStorage')
			}
		},
		updateAllGoodsState(state, goods) {
			// 循环更新购物车中每件商品的勾选状态
			state.cart.forEach(item => item.goods_state = goods)
			this.commit('m_cart/saveToStorage')
		},
		// // 根据 Id 从购物车中删除对应的商品信息
		// removeGoodsById(state, goods_id) {
		// 	// 调用数组的 filter 方法进行过滤
		// 	state.cart = state.cart.filter(x => x.goods_id !== goods_id)
		// 	// 持久化存储到本地
		// 	this.commit('m_cart/saveToStorage')
		// }
	},
	getters: {
		total(state) {
			return state.cart.reduce((acc, curr) => acc + curr.goods_count, 0)
		},
		// 全选
		isFullCheck(state) {
			return state.cart.every(item => item.goods_state === true)
		},
		// 总价结算
		checkedprice(state) {
			return state.cart.filter(item => item.goods_state === true).reduce((acc, curr) => acc + curr.goods_price *
				curr
				.goods_count, 0).toFixed(2)
		},
		checkedCount(state) {
			return state.cart.filter(goods => goods.goods_state === true).reduce((acc, curr) => acc + curr.goods_count,
				0)
		}
	}
}
